package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Spot;
import cn.wolfcode.wolf2w.query.SpotQuery;
import cn.wolfcode.wolf2w.repository.SpotRepository;
import cn.wolfcode.wolf2w.service.ISpotService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class SpotServiceImpl implements ISpotService{
    @Autowired
    private SpotRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Spot spot) {
        spot.setId(null);
        repository.save(spot);
    }

    @Override
    public void update(Spot spot) {
        repository.save(spot);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    /**
     * 查询一个
     * @param id
     * @return
     */
    @Override
    public Spot get(String id) {
        //orEls,查询id,存在就返回,不承诺在就返回null
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Spot> list() {
        //查询所有
        return repository.findAll();
    }

    @Override
    public Page<Spot> query(SpotQuery qo) {
        //分页查询
        //查询对象
        Query query = new Query();
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,Spot.class,query,pageable);

    }

    @Override
    public void saveOrUpdate(Spot spot) {
        if (StringUtils.hasLength(spot.getId())){
            this.update(spot);
        }else {
            //save
            this.save(spot);
        }
    }

}
